﻿#include "textedit.h"
#include <QPainter>
#include <QStyleOption>
#include <QTextCursor>
#include <QTextCharFormat>

TextEdit::TextEdit(QWidget *parent)
    : QTextEdit(parent), m_transparentBorder(false), m_backgroundColor(Qt::white),
      m_borderRadius(0), m_textFont("Arial", 12), m_textColor(Qt::black), m_textSize(12)
{
    // 初始化样式
    setStyleSheet("QTextEdit { border: none; }");
}

void TextEdit::setTransparentBorder(bool transparent)
{
    m_transparentBorder = transparent;
    update();
}

void TextEdit::setBackgroundColor(const QColor &color)
{
    m_backgroundColor = color;
    update();
}

void TextEdit::setBorderRadius(int radius)
{
    m_borderRadius = radius;
    update();
}

void TextEdit::setTextFont(const QFont &font)
{
    m_textFont = font;
    setFont(m_textFont);
}

void TextEdit::setTextColor(const QColor &color)
{
    if (m_textColor == color) {
        return; // 如果颜色相同，直接返回
    }

    m_textColor = color;

    // 使用 QTextCharFormat 设置文本颜色
    QTextCursor cursor = textCursor();
    QTextCharFormat format;
    format.setForeground(m_textColor);
    cursor.mergeCharFormat(format);
    setTextCursor(cursor);
}

void TextEdit::setTextSize(int size)
{
    m_textSize = size;
    m_textFont.setPointSize(m_textSize);
    setFont(m_textFont);
}

void TextEdit::paintEvent(QPaintEvent *event)
{
    QPainter painter(viewport());

    // 绘制背景
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(m_backgroundColor);
    painter.setPen(Qt::NoPen);
    painter.drawRoundedRect(rect(), m_borderRadius, m_borderRadius);

    // 调用基类的paintEvent以绘制文本
    QTextEdit::paintEvent(event);
}
